<script setup lang="ts">
import { ApiDetail } from '@/api/api-manage/detail'
import { speechToText } from '@/api/api-manage/stt'
import { message } from '@/utils/message'
import { dayjs, UploadFile, UploadRequestOptions } from 'element-plus'
import { generateApiLog } from '../../useApiLog'
import { addLog } from '@/api/api-manage/log'
import { useUserStore } from '@/store/modules/user'
import { getToken } from '@/utils/auth'

const props = defineProps<{
  data: ApiDetail
}>()

const fileList = ref<Array<UploadFile>>([])
const uploadRef = ref()
const resultText = ref('')
const processing = ref(false)

/**
 * 上传文件方法
 * @param options
 */
async function process(options: UploadRequestOptions) {
  if (props.data.enabledStatus != '1') {
    message('接口已停用, 请联系管理员开启', { type: 'warning' })
    return
  }
  resultText.value = ''
  processing.value = true

  const { file } = options
  const formData = new FormData()
  formData.append('file', file)
  formData.append('apiId', props.data.id.toString())

  message('正在处理音频', { type: 'info' })

  let startTime = performance.now()
  const requestTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
  let res = '0'
  let resCode = 500
  speechToText(formData)
    .then(({ data }) => {
      resultText.value = data
      message('操作成功', { type: 'success' })
      res = '1'
      resCode = 200
    })
    .catch((err) => {
      res = '0'
      resCode = 500
      message('接口存在问题无法调用', { type: 'error' })
    })
    .finally(() => {
      let endTime = performance.now()
      let duration = endTime - startTime
      const endDateTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
      let userBy = '在线体验'
      if (getToken() != null && getToken() != '') {
        userBy = useUserStore().username + userBy
      }
      const log = generateApiLog(
        props.data,
        requestTime,
        endDateTime,
        duration,
        userBy,
        res,
        resCode,
        '2'
      )
      addLog(log)
      processing.value = false
    })
}
</script>

<template>
  <div class="space-y-4">
    <el-upload
      ref="uploadRef"
      :file-list="fileList"
      :show-file-list="false"
      :http-request="process"
      accept="audio/*"
    >
      <el-button :loading="processing" type="primary">上传音频</el-button>
    </el-upload>
    <el-form :disabled="processing">
      <el-form-item label="语音识别结果">
        <el-input v-model="resultText" type="textarea" :rows="8" />
      </el-form-item>
    </el-form>
  </div>
</template>
